<template>
    <div>
        <div style="margin: 10px 0">
            <el-input style="width: 200px" placeholder="请输入商品名称" suffix-icon="el-icon-search"
                v-model="pagequery.proname"></el-input>
            <el-input style="width: 200px" placeholder="请输入商品分类" suffix-icon="el-icon-menu"
                v-model="pagequery.cname"></el-input>
            <el-input style="width: 200px" placeholder="请输入商品价格" suffix-icon="el-icon-search"
                v-model="pagequery.proprice"></el-input>
            <el-button type="primary" @click="load">搜索</el-button>
            <el-button type="info" @click="reset">重置</el-button>
        </div>
        <div style="margin: 10px 0">
            <el-button type="primary" @click="handleAdd">新增 <i class="el-icon-circle-plus-outline"></i></el-button>
            <el-button type="danger" @click="delBatch">批量删除 <i class="el-icon-remove-outline"></i></el-button>
        </div>
        <el-table @selection-change="handleSelectionChange" :data="tableData" border stripe
            :header-cell-style="{background:'#eee',color:'#000000'}">
            <el-table-column type="selection" width="68"></el-table-column>
            <el-table-column prop="id" label="ID" width="100"></el-table-column>
            <el-table-column prop="proname" label="商品名称" width="200"></el-table-column>
            <el-table-column prop="proprice" label="商品价格(¥)" width="130"></el-table-column>
            <!-- <el-table-column prop="pavatarUrl" label="商品图片" width="120"></el-table-column> -->
            <el-table-column prop="pavatarUrl" label="商品图片" width="200">
                <template slot-scope="scope">
                    <img :src="scope.row.pavatarUrl" style="width: 100px; height: 100px;">
                </template>
            </el-table-column>

            <el-table-column prop="category.cname" label="分类" width="150">
                <template slot-scope="scope">
                    <el-tag size="medium">
                        {{ scope.row.category.cname }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" width="100"></el-table-column>
            <el-table-column label="操作" width="330" align="center">
                <template v-slot:default="scope">
                    <el-button type="info" @click="handleDetails(scope.row)">详情 <i class="el-icon-info"></i></el-button>

                    <el-button type="success" @click="handleEdit(scope.row)">编辑 <i class="el-icon-edit"></i></el-button>
                    <el-popconfirm class="ml-5" confirm-button-text='确定' cancel-button-text='我再想想' icon="el-icon-info"
                        icon-color="red" title="您确定删除吗？" @confirm="del(scope.row.id)">
                        <!-- <el-button type="danger" @click="del(scope.row.id)">删除 <i class="el-icon-delete"></i></el-button> -->
                        <el-button type="danger" slot="reference">删除 <i class="el-icon-remove-outline"></i></el-button>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <div style="padding: 10px 0">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="pagequery.pageNum" :page-sizes="[5, 10, 20]" :page-size="pagequery.pageSize"
                layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
            <!-- Dialogs and other components remain similar to user management but adapted for products -->
        </div>
        <el-dialog title="商品信息" :visible.sync="dialogFormVisible" width="30%">
            <el-form ref="productForm" :model="form" :rules="rules" label-width="80px" size="small">
                <el-form-item prop="proname" label="商品名称">
                    <el-input v-model="form.proname" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item prop="proprice" label="商品价格">

                    <el-input v-model="form.proprice" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item prop="pavatarUrl" label="商品图片">
                    <!-- <el-input v-model="form.p_avatar_url" autocomplete="off"></el-input> -->
                    <template>
                        <el-upload class="avatar-uploader" action="http://localhost:9090/file/upload"
                            :show-file-list="false" :on-success="handleAvatarSuccess" :headers="uploadHeaders"
                            :before-upload="beforeUpload">
                            <img :src="form.pavatarUrl" class="avatar" style="width: 25px; height: 25px;">

                        </el-upload>
                    </template>
                </el-form-item>
                <el-form-item prop="cname" label="商品分类">
                    <el-select v-model="form.cid" placeholder="请选择分类">
                        <el-option v-for="category in categories" :key="category.id" :label="category.cname"
                            :value="category.id">
                        </el-option>
                    </el-select>

                </el-form-item>
                <!-- <el-form-item prop="Addvalue" label="详细信息">

                    <el-input v-model="form.Addvalue" autocomplete="off"></el-input>
                </el-form-item> -->
                <el-form-item prop="introduction" label="详细信息">
                    <el-input type="textarea" v-model="form.introduction" autocomplete="off" rows="4"></el-input>
                </el-form-item>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="save">确 定</el-button>
            </div>
        </el-dialog>
        <!-- 商品详细信息 -->
        <el-dialog title="商品详细信息" :visible.sync="detailsDialogVisible" width="50%">
            <el-form :model="detailsForm" label-width="120px" size="small">
                <el-form-item label="商品名称">
                    <el-input v-model="detailsForm.proname" readonly></el-input>
                </el-form-item>
                <el-form-item label="商品详情">
                    <!-- <el-input v-model="detailsForm.value" readonly ></el-input> -->
                    <el-input type="textarea" v-model="detailsForm.introduction" readonly :rows="7"
                        style="resize: none; height: 100px;"> <!-- 禁止调整大小并设置高度 -->
                    </el-input>
                </el-form-item>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="detailsDialogVisible = false">关闭</el-button>
            </div>
        </el-dialog>

    </div>

</template>


<script>
 import qs from "qs";
export default {
  components: {},
        props: {},
        data() {
            return {
                uploadHeaders: {"token": this.$store.state.uploadHeaders},
                dialogFormVisible: false,//新增的对话框
                detailsDialogVisible: false,//新增的对话框
                multipleSelection: [],//批量删除传递id
                detailsForm:{},
                form: {},//新增的表单
                categories: [],//分类
                tableData: [],//表格数据
                total: 0,
                pagequery: {  //分页查询条件
                    pageNum: 1,
                    pageSize: 5,
                    pro_name: "",
                    cname :"",
                    pro_price:""
                },
                rules: {
                    pro_name: [
                        {required: true, message: '请输入商品名', trigger: 'blur'},
                        {min: 3, max: 10, message: '长度不限', trigger: 'blur'}
                    ],
                    pro_price: [
                        {required: true, message: '请输入商品价格', trigger: 'blur'},
                        {min: 1, max: 20, message: '价格不限', trigger: 'blur'}
                    ],
                    p_avatar_url: [
                        { required: true, message: '图片不能为空', trigger: 'blur' },
                        { type: 'url', message: '请输入正确的图片文件', trigger: ['blur', 'change'] }
                    ],
                    cid: [
                        {required: true, message: '请选择分类', trigger: 'blur'},
                    ],
                  
                }
            };
        },
         computed: {},
        watch: {},
    methods: {
       
        //新增对话框的初始化
            handleAdd() {
                this.form = {}
                this.dialogFormVisible = true
                
            },
         //编辑对话框初始化
            handleEdit(row) {
                this.form = row
                // this.form.roleid = row.role.map(k => k.id)
                this.dialogFormVisible = true
            },
            //详情对话框
            handleDetails(row) {
              this.detailsForm.id = row.id;
              this.detailsForm.proname = row.proname;
              this.detailsForm.introduction=row.introduction
              // // 异步获取商品详细信息
              // this.request.get("/propertyvalue/" + row.id).then(res => {
              //   if (res.data) {
              //     this.detailsForm.value = res.data.value;
              //     // 确保数据加载后再显示对话框
                  this.detailsDialogVisible = true;
              //   } else {
              //     this.$message.error("无法加载商品详情");
              //   }
              //   console.log(this.detailsForm.value);
              // }).catch(error => {
              //   console.log(error);
              //   this.$message.error("加载数据失败");
              // });
            },

             //新增
            // save() {
            //     this.$refs['productForm'].validate((valid) => {
            //         if (valid) {
            //             this.request.post("/product/save", this.form).then(res => {
            //                     // this.detailsForm.proname=res.data.pro_name
            //                     // this.detailsForm.introduction=res.data.introduction
            //                     // this.productForm.introduction=res.data.introduction
            //                    if (res) {   
            //                     this.$message.success("保存成功")
            //                     this.dialogFormVisible = false
            //                     this.load()

                           
            //             }else {
            //                 this.$message.error("产品保存失败");
            //           }
            //         }).catch(error => {
            //           this.$message.error("产品保存请求失败: " + error);
            //       });
            //         } else {
            //             this.$message.error("商品信息请填写完整")
            //             return false;
            //         }
            //     });
            // },
        save() {
            // 检查表单数据中是否包含id，存在id则认为是更新，否则为新增
            if (this.form.id) {
                this.updateProduct(); // 调用更新商品的方法
            } else {
                this.addProduct(); // 调用添加商品的方法
            }
        },

        // 添加商品
        addProduct() {
            this.$refs['productForm'].validate((valid) => {
                if (valid) {
                    this.request.post("/product/add", this.form).then(res => {
                        if (res ) {
                            this.$message.success("商品添加成功");
                            this.dialogFormVisible = false;
                            this.load();
                        } else {
                            this.$message.error("商品添加失败：" + (res.data.message || 'Unknown Error'));
                        }
                    }).catch(error => {
                        this.$message.error("添加请求失败: " + error);
                    });
                } else {
                    this.$message.error("请完整填写商品信息");
                }
            });
        },

        // 更新商品
        updateProduct() {
            this.$refs['productForm'].validate((valid) => {
                if (valid) {
                    this.request.post("/product/update", this.form).then(res => {
                        if (res ) {
                            this.$message.success("商品更新成功");
                            this.dialogFormVisible = false;
                            this.load();
                        } else {
                            this.$message.error("商品更新失败：" + (res.data.message || 'Unknown Error'));
                        }
                    }).catch(error => {
                        this.$message.error("更新请求失败: " + error);
                    });
                } else {
                    this.$message.error("请完整填写商品信息");
                }
            });
        },

         //单个删除
            del(id) {
                this.request.delete("/product/" + id).then(res => {
                    console.log(res)
                    if (res) {
                        this.$message.success("删除成功")
                        this.load()
                    } else {
                        this.$message.error("删除失败")
                    }
                })
            },
             //批量删除
            delBatch() {
                let ids = this.multipleSelection.map(v => v.id)  // [{}, {}, {}] => [1,2,3]
                if (ids.length === 0) {
                    this.$message.warning("请选择删除的商品")
                    return
                }
                this.request.post("/product/del/batch", ids).then(res => {
                    if (res) {
                        this.$message.success("批量删除成功")
                        this.load()
                    } else {
                        this.$message.error("批量删除失败")
                    }
                })
            },
       reset() {
                this.pagequery = {
                    pageNum: 1,
                    pageSize: 5,
                    pro_name: "",
                    cname: "",
                    pro_price: ""
                    
                }
                this.load()
            },
            load() {
                this.request.get("/product/page?" + qs.stringify(this.pagequery)).then(res => {
                    if (res.code === 200) {
                        this.total = res.data.total
                        this.tableData = res.data.records
                        this.tableData.forEach(product=>{
                          console.log(" 商品id: "+product.id+" 商品名称："+product.proname+" 商品价格："+product.proprice+
                          " 商品url: "+product.pavatarUrl+" 分类名：",product.category.cname,"创建时间",product.createDate,"详情：",product.introduction)
                        }
                        )
                    }
                })
                this.request.get("/category" ).then(res => {
                    this.categories = res.data
                    this.categories.forEach(category => {
                console.log("分类ID：" + category.id + "，分类名称：" + category.cname);
                });
                })
            },
        handleSizeChange(pageSize) {
                console.log(pageSize)
                this.pagequery.pageSize = pageSize
                this.load()
            },
         handleCurrentChange(pageNum) {
                console.log(pageNum)
                this.pagequery.pageNum = pageNum
                this.load()
            },
             handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            handleAvatarSuccess(res) {
                this.form.pavatarUrl = res.data
                console.log(res.data)
            },
            beforeUpload(){
                this.uploadHeaders ={"token": localStorage.getItem("token") ? JSON.parse(localStorage.getItem("token")) : {}}
            },
            
    },
    created() {
        this.load();
    }
};
</script>

